package auth

import (
	"data/view/auth/auth_const"
	"data/view/user"
	"plug/myauth"
	"public/message"
	"public/tools"

	"github.com/ant0ine/go-json-rest/rest"
)

/*
	拉取全部权限
*/
func GetAll(w rest.ResponseWriter, r *rest.Request) {
	var req GetAllParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := CheckRoleAuth(u.Business_role, auth_const.M_7, auth_const.L_A, auth_const.L_B, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	msg := message.GetSuccessMsg()
	msg.Data = OnGetAllAuth()
	w.WriteJson(msg)
}

/*
	更新全部权限
*/
func Update(w rest.ResponseWriter, r *rest.Request) {
	var req UpdateParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token, req.Module, req.Auth_level) || req.Role == 0 {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}

	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := CheckRoleAuth(u.Business_role, auth_const.M_7, auth_const.L_A, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	// ret := myauth.UpdateAuthConfigInfo("UPDATE authority_config_tbl SET auth_level=?,des=? WHERE role=? AND module=?",
	// req.Auth_level, auth_const.UserRoleMap[req.Role]+"_"+auth_const.ModulMap[req.Module]+"_"+auth_const.AuthMap[req.Auth_level], req.Role, req.Module)
	rconfig := user.GetRoleConfigInfo()
	var auth myauth.Authority_config_tbl
	auth.Role = req.Role
	auth.Module = req.Module
	auth.Auth_level = req.Auth_level
	auth.Des = rconfig[req.Role].Desc + "_" + auth_const.ModulMap[req.Module] + "_" + auth_const.AuthMap[req.Auth_level]

	ret := myauth.SaveAuthConfigInfo(auth)
	if !ret {
		w.WriteJson(message.GetErrorMsg(message.UnknownError))
		return
	}
	w.WriteJson(message.GetSuccessMsg())
}
